package com.itcast.mallapplet.service.impl;

import com.itcast.applet.entity.OrderDity;
import com.itcast.admin.entity.Seckill;
import com.itcast.applet.dto.SeckillDTO;
import com.itcast.applet.entity.Order;
import com.itcast.context.BaseContext;
import com.itcast.mallapplet.mapper.OrderMapper;
import com.itcast.mallapplet.mapper.SeckillMapper;
import com.itcast.mallapplet.service.SeckillService;
import io.swagger.v3.oas.annotations.servers.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {

     @Autowired
     private SeckillMapper seckillMapper;
     @Autowired
     private OrderMapper orderMapper;

    //根据id查询单个秒杀商品
    public Seckill seckillQuery(Long id) {
        Seckill seckill = seckillMapper.seckillQuery(id);
        return seckill;
    }

    //查询全部秒杀商品 TODO 时间判断
    public List<Seckill> seckillQueryAll() {
        List<Seckill> seckillList = seckillMapper.seckillQueryAll();
        return seckillList;
    }

    //秒杀商品下单 - 秒杀商品也应当减少库存
    @Transactional
    public void seckillAdd(SeckillDTO seckillDTO) {
        Seckill seckill = seckillMapper.seckillQuery(seckillDTO.getId());
        Double price = seckill.getPrice() * seckillDTO.getNumber();
        Order order = Order.builder()
                .price(price)
                .number(seckillDTO.getNumber())
                .addressId(seckillDTO.getAddressId())
                .status(1)
                .createTime(LocalDateTime.now())
                .userId(BaseContext.getCurrentId())
                .build();
        //添加订单
        orderMapper.orderAdd(order);

        //减少库存,更新秒杀商品表
        seckill.setNumber(seckill.getNumber() - seckillDTO.getNumber());
        seckillMapper.seckillUpdate(seckill);

        //构建订单分表
        OrderDity orderDity = OrderDity.builder()
                .name(seckill.getName())
                .shopId(seckill.getId())
                .price(seckill.getPrice())
                .number(seckillDTO.getNumber())
                .orderId(order.getId())
                .build();

        orderMapper.orderDity(orderDity);
    }

}
